#include "tcp_server_select.h"
#include <sys/select.h>

int main(int argc, char *argv[])
{
    int fd_s = tcp_server_init("0", 8888, PF_INET);
    ERROR_CHECK(-1, fd_s, "tcp_server_init");
    fd_set r_set, b_set;
    FD_ZERO(&b_set);
    FD_SET(fd_s, &b_set);
    int nfds = fd_s + 1;
    char buf[1024];
    while (1)
    {
        r_set = b_set;
        if (-1 == select(nfds, &r_set, NULL, NULL, NULL))
        {
            perror("select");
            return -1;
        }
        for (size_t fd = 0; fd < nfds; fd++)
        {
            if (!FD_ISSET(fd, &r_set))
                continue;
            if (FD_ISSET(fd_s, &r_set)) // 判断监听套接字
            {
                int fd_cnd = tcp_server_wait(fd_s);
                if (-1 == fd_cnd)
                {
                    perror("wait");
                    continue;
                }
                FD_SET(fd_cnd, &b_set);
                nfds = fd_cnd >= nfds ? fd_cnd + 1 : nfds;
            }
            else
            {

                if (-1 == sendfile(fd))
                {
                    perror("sendfile");
                    FD_CLR(fd, &b_set);
                    nfds = fd == (nfds - 1) ? nfds - 1 : nfds;
                    close(fd);
                    continue;
                }
                puts("over");
            }
        }
    }
    return 0;
}
